﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.Data.Entity;
using System.Data.EntityClient;
using System.IO;
using System.Threading;
using Helpers;


namespace BackUpService
{
    public partial class Service1 : ServiceBase
    {
        private System.Timers.Timer timer = new System.Timers.Timer();

        private EntityConnection entityConnection = null;

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            #region Init connection
            EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder();
            
            ecsb.Name = "DosvidEntities";

            entityConnection = new EntityConnection(ecsb.ConnectionString);

            entityConnection.Open();

            DAL.BAL.Business.Init(entityConnection);
            #endregion

            timer.Interval = 55000;

            timer.Elapsed += timer_Elapsed;

            timer.Enabled = true;

            EventLog.WriteEntry("Started");
        }

        protected override void OnStop()
        {
            timer.Enabled = false;

            entityConnection.Close();

            EventLog.WriteEntry("Stopped");
        }

        private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            DAL.Models.BackUpHistory bh = null;

            try
            {
                timer.Enabled = false;

                string time = string.Empty;

                bool needBackup = false;

                //EventLog.WriteEntry(string.Format("Timer tick {0}", DateTime.Now.ToString()));

                DAL.BAL.Business.Refresh(System.Data.Objects.RefreshMode.ClientWins, DAL.BAL.Business.MyEntities.BackupOptions);

                DAL.BAL.Business.Refresh(System.Data.Objects.RefreshMode.ClientWins, DAL.BAL.Business.MyEntities.Backup);

                var timeOption = (from n in DAL.BAL.Business.GetBackupOptions()
                                  where n.Id == 1
                                  select n).FirstOrDefault();

                if (timeOption != null)
                    time = timeOption.Value;

                EventLog.WriteEntry(string.Format("Selected time {0}", time));

                TimeSpan t = new TimeSpan();

                if (TimeSpan.TryParse(time, out t))
                {

                    EventLog.WriteEntry(string.Format("Time is parsed"));


                    if ((DateTime.Now.TimeOfDay >= t) && ((from n in DAL.BAL.Business.GetBackupHistory()
                                                           where n.Status == "OK" && n.BackupDate.Date == DateTime.Now.Date
                                                           select n).Count() == 0))
                    {
                        EventLog.WriteEntry("First condition is passed");

                        needBackup = true;
                    }
                    else
                    {
                        if ((from n in DAL.BAL.Business.GetBackupHistory()
                             where n.Status == "OK" && ((n.BackupDate.Date == DateTime.Now.AddDays(-1).Date) ||
                                                        (n.BackupDate.Date == DateTime.Now.Date))
                             select n).Count() == 0)
                        {
                            needBackup = true;

                            EventLog.WriteEntry("Second condition is passed");
                        }
                    }

                    if (needBackup)
                    {
                        bh = new DAL.Models.BackUpHistory();

                        DAL.BAL.Business.AddObject("BackUpHistories", bh);

                        bh.BackUpType = (from n in DAL.BAL.Business.GetBackupTypes()
                                         where n.Id == 1
                                         select n).FirstOrDefault();

                        bh.BackupDate = DateTime.Now;

                        string localPath = System.Environment.GetEnvironmentVariable("TEMP", EnvironmentVariableTarget.Machine);

                        localPath = localPath.EndsWith("\\") == true ? localPath : localPath + "\\";

                        if (File.Exists(localPath + "Dosvid.bak"))
                            File.Delete(localPath + "Dosvid.bak");

                        if (File.Exists(localPath + "Dosvid.bak.gz"))
                            File.Delete(localPath + "Dosvid.bak.gz");

                        DAL.BAL.Business.sp_BackupCustom(localPath + "Dosvid.bak");

                        CompressFiles.Compress(new System.IO.FileInfo(localPath + "Dosvid.bak"));

                        try
                        {
                            FtpHelper.DeleteFile("Dosvid.bak.gz");
                        }
                        catch(Exception ex)
                        {
                            EventLog.WriteEntry(ex.Message, EventLogEntryType.Error);
                        }

                        Thread.Sleep(30000);

                        FtpHelper.UploadFile(localPath + "Dosvid.bak.gz");

                        bh.Status = "OK";

                        DAL.BAL.Business.Save();

                        EventLog.WriteEntry("Backup is done and saved");

                    }
                }
            }
            catch (Exception e1)
            {
                EventLog.WriteEntry(e1.Message, EventLogEntryType.Error);

                if (bh != null)
                {
                    bh.Status = e1.InnerException != null ? e1.InnerException.Message : e1.Message;

                    DAL.BAL.Business.Save();
                }
            }
            finally
            {
                timer.Enabled = true;
            }
        }
    }
}
